package com.hxc.pay.wx.core;

import com.alibaba.fastjson.JSON;
import com.hxc.pay.CommonPayTemplate;
import com.hxc.pay.wx.config.WxPayProperties;
import com.hxc.pay.wx.dto.CloseDto;
import com.hxc.pay.wx.dto.RefundAmount;
import com.hxc.pay.wx.dto.RefundDto;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URISyntaxException;

public class WxCommonPayTemplate implements CommonPayTemplate {


    private WxPayProperties wxPayProperties;
    private CloseableHttpClient httpClient;

    public WxCommonPayTemplate(WxPayProperties wxPayProperties, CloseableHttpClient httpClient) {
        this.wxPayProperties = wxPayProperties;
        this.httpClient = httpClient;
    }

    @Override
    public String queryOrder(String outTradeNo) {
        //请求URL

        String resStr = null;
        try {
            URIBuilder uriBuilder = new URIBuilder("https://api.mch.weixin.qq.com/v3/pay/transactions/out-trade-no/"+outTradeNo);
            uriBuilder.setParameter("mchid", wxPayProperties.getMchId());

            //完成签名并执行请求
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            httpGet.addHeader("Accept", "application/json");
            CloseableHttpResponse response = httpClient.execute(httpGet);

            resStr = "";
            try {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 200) {
                    System.out.println("success,return body = " + EntityUtils.toString(response.getEntity()));
                    resStr = EntityUtils.toString(response.getEntity());
                } else if (statusCode == 204) {
                    System.out.println("success");
                } else {
                    System.out.println("failed,resp code = " + statusCode+ ",return body = " + EntityUtils.toString(response.getEntity()));

                }
            } finally {
                response.close();
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return resStr;
    }

    @Override
    public String refund(Integer refund, Integer total, String outTradeNo, String outRefundNo) {
        HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/refund/domestic/refunds");
        // 请求body参数
        RefundAmount refundAmount = RefundAmount.builder()
                .refund(1)
                .total(1)
                .currency("CNY")
                .build();

        RefundDto refundDto = RefundDto.builder()
                .amount(refundAmount)
                .out_refund_no(outRefundNo) //商家后台自定义退款单号
                .out_trade_no(outTradeNo) //订单号
                .notify_url(wxPayProperties.getNotifyUrl()) //退款通知接口
                .build();




        String reqdata = JSON.toJSONString(refundDto);
        StringEntity entity = new StringEntity(reqdata,"utf-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        httpPost.setHeader("Accept", "application/json");

        //完成签名并执行请求
        String resStr = null;
        try {
            CloseableHttpResponse response = httpClient.execute(httpPost);

            resStr = "";
            try {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 200) { //处理成功
                    System.out.println("success,return body = " + EntityUtils.toString(response.getEntity()));
                    resStr = EntityUtils.toString(response.getEntity());
                } else if (statusCode == 204) { //处理成功，无返回Body
                    System.out.println("success");
                } else {
                    System.out.println("failed,resp code = " + statusCode+ ",return body = " + EntityUtils.toString(response.getEntity()));

                }
            } finally {
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return resStr;
    }

    @Override
    public void close(String outTradeNo) {
        //String our_trade_no = "AEFA234DAFD2342342FRADFAS5";
        String url = "https://api.mch.weixin.qq.com/v3/pay/transactions/out-trade-no/"+outTradeNo+"/close";
        HttpPost httpPost = new HttpPost(url);
        // 请求body参数

        CloseDto closeDto = CloseDto.builder()
                .mchid(wxPayProperties.getMchId())
                .build();


        String reqdata = JSON.toJSONString(closeDto);
        StringEntity entity = new StringEntity(reqdata,"utf-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        httpPost.setHeader("Accept", "application/json");

        //完成签名并执行请求
        try {
            CloseableHttpResponse response = httpClient.execute(httpPost);

            try {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 200) { //处理成功
                    System.out.println("success,return body = " + EntityUtils.toString(response.getEntity()));
                } else if (statusCode == 204) { //处理成功，无返回Body
                    System.out.println("success");
                } else {
                    System.out.println("failed,resp code = " + statusCode+ ",return body = " + EntityUtils.toString(response.getEntity()));

                }
            } finally {
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
